package comlib.compdigitec.libvlcandroidsample;

import java.lang.ref.WeakReference;

import org.videolan.libvlc.EventHandler;
import org.videolan.libvlc.IVideoPlayer;
import org.videolan.libvlc.LibVLC;
import org.videolan.libvlc.LibVlcUtil;
import org.videolan.libvlc.Media;
import org.videolan.libvlc.MediaList;

import com.doctor.ui.R;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

public class VideoActivity extends Activity implements SurfaceHolder.Callback,
        IVideoPlayer{
    public final static String TAG = "LibVLCAndroidSample/VideoActivity";

    public final static String LOCATION = "com.compdigitec.libvlcandroidsample.VideoActivity.location";

    private String mFilePath;

    // display surface
    private SurfaceView mSurface;
    private SurfaceHolder holder;

    // media player
    private LibVLC libvlc;
    private int mVideoWidth;
    private int mVideoHeight;
    private final static int VideoSizeChanged = -1;
    
    
    private static final int MSG_UPDATE=1,MSG_HIDE=2;
    private Handler handler;
    private boolean isPlaying=true;
    private View myMediaController;
    //后退、暂停(播放)、前进按钮
    private ImageButton backBtn,pauseBtn,forwordBtn;
    //播放进度条
    private SeekBar mSeekBar;
    //播放时长、总时长
    private TextView currentTime,totalTime;
    //视频总时长(ms)
    private long length;
    //快进快退步长15s,隐藏播放控制器3s
    private static final long STEP=15000,HIDE_DUATION=3000;
    //已播放的时间
    private long time;
    
    

    /*************
     * Activity
     *************/

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sample);

        // Receive path to play from intent
        Intent intent = getIntent();
        mFilePath = intent.getExtras().getString(LOCATION);

        Log.d(TAG, "Playing back " + mFilePath);

        mSurface = (SurfaceView) findViewById(R.id.surface);
        holder = mSurface.getHolder();
        holder.addCallback(this);
        
        handler=new Handler(){
        	@Override
        	public void handleMessage(Message msg) {
        		// TODO Auto-generated method stub
        		super.handleMessage(msg);
        		if (libvlc==null || length<=0) {
					return;
				}
        		
        		switch (msg.what) {
					
        		case MSG_HIDE:
        			if (myMediaController.getVisibility()!=View.GONE) {
						myMediaController.setVisibility(View.GONE);
					}
        			break;
        		
				case MSG_UPDATE:
					long timeTemp=libvlc.getTime();  //已经播放的秒数
					if (time!=timeTemp) {
						time=timeTemp;
						currentTime.setText(timeString(time/1000));
						//进度条值
						int value=(int) (100*(time/1000)/length);
						mSeekBar.setProgress(value);
					}
					handler.sendEmptyMessageDelayed(MSG_UPDATE, 1000);
					break;
					
				default:
					break;
				}
        	}
        };
        //保持屏幕常亮
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        createPlayer(mFilePath);
    }
    
    @Override
    protected void onStop() {
    	// TODO Auto-generated method stub
    	super.onStop();
    	if (libvlc.isPlaying()) {
    		libvlc.pause();
    		pauseBtn.setImageResource(android.R.drawable.ic_media_play);
		}
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        setSize(mVideoWidth, mVideoHeight);
    }

    @Override
    protected void onResume() {
        super.onResume();
//        createPlayer(mFilePath);
        if (libvlc!=null && length>0 && !libvlc.isPlaying()) {
        	pauseBtn.setImageResource(android.R.drawable.ic_media_pause);
			libvlc.play();
			handler.sendEmptyMessage(MSG_UPDATE);
		}
    }

    @Override
    protected void onPause() {
        super.onPause();
//        releasePlayer();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        releasePlayer();
    }

    /*************
     * Surface
     *************/

    public void surfaceCreated(SurfaceHolder holder) {
    }

    public void surfaceChanged(SurfaceHolder surfaceholder, int format,
            int width, int height) {
        if (libvlc != null)
            libvlc.attachSurface(holder.getSurface(), this);
    }

    public void surfaceDestroyed(SurfaceHolder surfaceholder) {
    }

    private void setSize(int width, int height) {
        mVideoWidth = width;
        mVideoHeight = height;
        if (mVideoWidth * mVideoHeight <= 1)
            return;

        if(holder == null || mSurface == null)
            return;

        // get screen size
        int w = getWindow().getDecorView().getWidth();
        int h = getWindow().getDecorView().getHeight();

        // getWindow().getDecorView() doesn't always take orientation into
        // account, we have to correct the values
        boolean isPortrait = getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT;
        if (w > h && isPortrait || w < h && !isPortrait) {
            int i = w;
            w = h;
            h = i;
        }

        float videoAR = (float) mVideoWidth / (float) mVideoHeight;
        float screenAR = (float) w / (float) h;

        if (screenAR < videoAR)
            h = (int) (w / videoAR);
        else
            w = (int) (h * videoAR);

        // force surface buffer size
        holder.setFixedSize(mVideoWidth, mVideoHeight);

        // set display size
        LayoutParams lp = mSurface.getLayoutParams();
        lp.width = w;
        lp.height = h;
        mSurface.setLayoutParams(lp);
        mSurface.invalidate();
    }

    @Override
    public void setSurfaceLayout(int width, int height, int visible_width,
            int visible_height, int sar_num, int sar_den) {
        Message msg = Message.obtain(mHandler, VideoSizeChanged, width, height);
        msg.sendToTarget();
    }
    
    
    /*************
     * Player
     *************/

    private void createPlayer(String media) {
        releasePlayer();
        try {
//            if (media.length() > 0) {
//                Toast toast = Toast.makeText(this, media, Toast.LENGTH_LONG);
//                toast.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0,
//                        0);
//                toast.show();
//            }

            // Create a new media player
            libvlc = LibVLC.getInstance();
            libvlc.setHardwareAcceleration(LibVLC.HW_ACCELERATION_DISABLED);
            libvlc.setSubtitlesEncoding("");
            libvlc.setAout(LibVLC.AOUT_OPENSLES);
            libvlc.setTimeStretching(true);
            libvlc.setVerboseMode(true);
            if(LibVlcUtil.isGingerbreadOrLater())
                libvlc.setVout(LibVLC.VOUT_ANDROID_WINDOW);
            else
                libvlc.setVout(LibVLC.VOUT_ANDROID_SURFACE);
            LibVLC.restart(this);
            EventHandler.getInstance().addHandler(mHandler);
            holder.setKeepScreenOn(true);
            MediaList list = libvlc.getMediaList();
            list.clear();
            Media mMedia=new Media(libvlc, LibVLC.PathToURI(media));
            list.add(mMedia, false);
            libvlc.playIndex(0);
            
            myMediaController=findViewById(R.id.my_media_controller);
            backBtn=(ImageButton) findViewById(R.id.rew);
            backBtn.setOnClickListener(onClick);
            pauseBtn=(ImageButton) findViewById(R.id.pause);
            pauseBtn.setImageResource(android.R.drawable.ic_media_pause);
            pauseBtn.setOnClickListener(onClick);
            
            forwordBtn=(ImageButton) findViewById(R.id.ffwd);
            forwordBtn.setOnClickListener(onClick);
            currentTime=(TextView) findViewById(R.id.time_current);
            mSeekBar=(SeekBar) findViewById(R.id.mediacontroller_progress);
            mSeekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {				
				@Override
				public void onStopTrackingTouch(SeekBar arg0) {
					// TODO Auto-generated method stub
					
				}
				
				@Override
				public void onStartTrackingTouch(SeekBar arg0) {
					// TODO Auto-generated method stub
					
				}
				
				@Override
				public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
					// TODO Auto-generated method stub
					//进度条的值改变
					if (arg2 && libvlc!=null && length>0) {
						//人工拖动进度条
						long time=(long) ((arg1/100f)*length);
						libvlc.setTime(time*1000);
						currentTime.setText(timeString(time));
					}
				}
			});
            totalTime=(TextView) findViewById(R.id.time);
            
            length=mMedia.getLength()/1000;  //总时长(s)
            if (length<0) {
				return;
			}
            totalTime.setText(timeString(length));
            //隔1s发送一个空消息来更新进度条和播放时间
            handler.sendEmptyMessageDelayed(MSG_UPDATE, 1000);
            handler.sendEmptyMessageDelayed(MSG_HIDE, HIDE_DUATION);
            
        } catch (Exception e) {
//            Toast.makeText(this, "Error creating player!", Toast.LENGTH_LONG).show();
        }
    }

    
    private OnClickListener onClick=new OnClickListener() {		
		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			if (libvlc==null || length<=0) {
				return;
			}
			
			if (arg0==backBtn) {
				//后退
				long gotoTime=libvlc.getTime()-STEP;
				if (gotoTime>=0) {
					libvlc.setTime(gotoTime);
				}
			} else if (arg0==forwordBtn) {
				//前进
				long gotoTime=libvlc.getTime()+STEP;
				if (gotoTime<=length*1000) {
					libvlc.setTime(gotoTime);
				}
			} else if (arg0==pauseBtn) {
				//播放或是暂停
				if (libvlc.isPlaying()) {
					libvlc.pause();
					pauseBtn.setImageResource(android.R.drawable.ic_media_play);
				} else {
					libvlc.play();
					handler.sendEmptyMessage(MSG_UPDATE);
					pauseBtn.setImageResource(android.R.drawable.ic_media_pause);
				}
			}
		}
	};
    
    
    /**
     * 时间格式
     * @param time 秒数
     * @return mm:ss格式的时间
     */
    private String timeString(long time){
    	long second=time%60; //秒数
        String secondString=(second==0?"00":(second<10?"0"+second:second+""));
        return (time/60)+":"+secondString;
    }
    
    
    private void releasePlayer() {
        if (libvlc == null)
            return;
        EventHandler.getInstance().removeHandler(mHandler);
        libvlc.stop();
        libvlc.detachSurface();
        holder = null;
        libvlc = null;

        mVideoWidth = 0;
        mVideoHeight = 0;
    }

    /*************
     * Events
     *************/

    private Handler mHandler = new MyHandler(this);

    private class MyHandler extends Handler {
        private WeakReference<VideoActivity> mOwner;

        public MyHandler(VideoActivity owner) {
            mOwner = new WeakReference<VideoActivity>(owner);
        }

        @Override
        public void handleMessage(Message msg) {
            VideoActivity player = mOwner.get();

            // SamplePlayer events
            if (msg.what == VideoSizeChanged) {
                player.setSize(msg.arg1, msg.arg2);
                return;
            }

            // Libvlc events
            Bundle b = msg.getData();
            switch (b.getInt("event")) {
            case EventHandler.MediaPlayerEndReached:
                Log.d(TAG, "MediaPlayerEndReached");
//                player.releasePlayer();
                libvlc.pause();
                pauseBtn.setImageResource(android.R.drawable.ic_media_pause);
                break;
            case EventHandler.MediaPlayerPlaying:
            case EventHandler.MediaPlayerPaused:
            case EventHandler.MediaPlayerStopped:
            default:
                break;
            }
        }
    }

    @Override
    public void eventHardwareAccelerationError() {
        // Handle errors with hardware acceleration
        this.releasePlayer();
//        Toast.makeText(this, "Error with hardware acceleration", Toast.LENGTH_LONG).show();
    }

    @Override
    public int configureSurface(Surface surface, int width, int height, int hal) {
        Log.d(TAG, "configureSurface: width = " + width + ", height = " + height);
        if (LibVlcUtil.isICSOrLater() || surface == null)
            return -1;
        if (width * height == 0)
            return 0;
        if(hal != 0)
            holder.setFormat(hal);
        holder.setFixedSize(width, height);
        return 1;
    }
    
	
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		if (event.getAction()==MotionEvent.ACTION_DOWN) {
			if (libvlc!=null && length>0) {
				if (myMediaController.getVisibility()!=View.VISIBLE) {
					myMediaController.setVisibility(View.VISIBLE);
				}
				handler.removeMessages(MSG_HIDE);
				handler.sendEmptyMessageDelayed(MSG_HIDE, HIDE_DUATION);
			}
		}
		return super.onTouchEvent(event);
	}
	
}
